const WebSocketServer = require("websocket").server;
const http = require("http");
const port = 8000;
let time = 0;

// 创建服务器
const server = http.createServer();
server.listen(port, () => {
  console.log(
    `${new Date().toLocaleDateString()} Server is listening on port ${port}`
  );
});

// websocket 服务器
const wsServer = new WebSocketServer({
  httpServer: server,
});

// 建立连接
wsServer.on("request", (request) => {
  // 当前的连接
  console.log(request.origin, "=======request.origin=======");
  const connection = request.accept(null, request.origin);
  console.log(`${new Date().toLocaleDateString()} 已经建立连接`);

  //心跳💓 就30s一个吧
  setInterval(() => {
    const obj = {
      value: "心跳💓" + time++,
    };
    connection.send(JSON.stringify(obj));
  }, 30000);
  connection.sendUTF("Hello, client!");
  // 监听客户端发来的的消息
  connection.on("message", (message) => {
    if (message.type === "utf8") {
      //文本消息
      console.log("Received Message: " + message.utf8Data);
      // connection.sendUTF(message.utf8Data);
    } else if (message.type === "binary") {
      // binary 二进制流数据
      console.log(
        "Received Binary Message of " + message.binaryData.length + " bytes"
      );
      // connection.sendBytes(message.binaryData);
    }

    //转发到其他客户端
    wsServer.connections.forEach(function (client) {
      if (client !== connection) {
        client.send(message.binaryData);
      }
    });
  });

  // 监听当前连接 当断开链接(网页关闭) 触发
  connection.on("close", (reasonCdoe, description) => {
    console.log(
      `${new Date().toLocaleDateString()} ${connection.remoteAddress} 断开链接`
    );
  });
});
